package com.tiny_wind.resource_manager.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.tiny_wind.resource_manager.utility.GaJJwtManager;
import com.tiny_wind.resource_manager.utility.GaLogManager;
import com.tiny_wind.resource_manager.utility.ResponseCodeManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.lang.Nullable;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class TokenInterceptor implements HandlerInterceptor {
	private Logger logger = LogManager.getLogger(this.getClass());
	private static String TAG = "TokenIntercreptor";
	// 之前
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		GaLogManager.v_c(TAG,"PATH","preHandle");
		if(CorsUtils.isPreFlightRequest(request)) {
			return true;
		}
		String token = request.getHeader(GaJJwtManager.ms_authKey);
		String info = String.format("TokenIntercrept/preHandle1111,token is: %s", token);
		if (token == null) {
			logger.warn("TokenIntecrept/preHandle,no token.");
			// 重定向返回登录失败信息.
			// 该方法只能用get请求来处理.
			 String url = request.getContextPath() + "/User/NoToken?code=-100";
			GaLogManager.v_c(TAG,"Path","redirect to: %s",url);
			response.sendRedirect(url);
			response.flushBuffer();
			return false;
		} else {
			Map<String, Claim> map = null;
			try {
				map = GaJJwtManager.verifyToken(token);
//				map = GaJJwtManager.parseToken(token);
			} catch (Exception e) {
				String url = String.format("%s/User/NoToken?code=%d",request.getContextPath(), ResponseCodeManager.errorCode_expiredToken);
				GaLogManager.v_c(TAG,"Path","token:%s is expired,redirect to: %s",token,url);
				//Question:不清楚这里为什么发送的请求是POST的.
				response.sendRedirect(url);
				response.flushBuffer();
				return false;
			}
			Claim claim = map.get("userId");
			Integer userId = claim.asInt();
			info = String.format("TokenIntercrept/preHandle1111,user id is: %d", userId);
			request.setAttribute("userId", userId);
			logger.info(info);

		}
		return true;
	}

	// 执行后
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
		String info = String.format("TokenIntercrept/postHandle");
		logger.info(info);
	}

	// 清理
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
		String info = String.format("TokenIntercrept/afterCompletion");
		logger.info(info);
	}

}
